﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LCUV;
using System.Data;
using System.Data.OleDb;
using System.IO;
using Oracle.DataAccess.Client;

namespace sWarranty.WEB
{
    public partial class ShopREG : System.Web.UI.Page
    {
        public string _currentUserEmpNo = "";
        public string _currentUserAuthority = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            string m = "0";
            string s = "0";
            _currentUserEmpNo = GetUserLoginEmpNo();
            if (!IsPostBack)
            {
                LoadArea();
                Session["filePath"] = "";
                Session["fileName"] = Guid.NewGuid().ToString();
            }
            try
            {
                m = Request.QueryString["m"].ToString();
                s = Request.QueryString["s"].ToString();
            }
            catch (Exception)
            {
            }
            if (m == "1" && !string.IsNullOrEmpty(s))
            {
                chkEnable.Visible = true;
                Session["UrltoFw"] = "ShopREG.aspx?m=1&s=" + s;
                lblTitle.Text = "Modify Shop Information";
                if (!IsPostBack)
                    LoadDataInModifyMode(s);
            }
            else
            {
                lblShopCode.Text = DBAction.GetNewShopCode(0);
                Session["UrltoFw"] = "ShopREG.aspx";
            }

            string updateValuesScript =
              @"function updateValues(popupValues)
                {
                        //popupValues[0] = VN000990001B,VN000990001B,VN000990001B,VN000990001B

                      var ReturnValue = popupValues[0];
                      document.getElementById('txtBillCode').value = ReturnValue;
                      document.getElementById('txtBillTo2').value = ReturnValue;
                }";
            this.ClientScript.RegisterStartupScript(Page.GetType(),
            "UpdateValues", updateValuesScript.ToString(), true);
            if (s != "0")
                btnFindBill.Attributes.Add("onclick", "openPopUp('FindBill.aspx?d=" + s + "','open')");
            else
                btnFindBill.Attributes.Add("onclick", "openPopUp('FindBill.aspx','open')");

            string updateValuesScript2 =
              @"function updateValues2(popupValues2)
                {
                        //format as: popupValues2[0] = proviceID&Pname|districtID&Dname;
                        var ReturnValue2 = popupValues2[0];
                        var lines2 = (ReturnValue2).split('|');
                        var p = '';
                        var d = '';
                        var provinceName = '';
                        var provinceID = '';
                        var districtName = '';
                        var districtID = '';
                        $.each(lines2, function (key, line) {
                            p = lines2[0];
                            d = lines2[1];
                        });
                        lines2 = (p).split('&');
                        $.each(lines2, function (key, line) {
                            provinceID = lines2[0];
                            provinceName = lines2[1];
                        });
                        lines2 = (d).split('&');
                        $.each(lines2, function (key, line) {
                            districtID = lines2[0];
                            districtName = lines2[1];
                        });
                   document.getElementById('txtProvince').value = provinceName;
                   document.getElementById('txtProvince2').value = provinceID;
                   document.getElementById('txtDistrict').value = districtName;
                   document.getElementById('txtDistrict2').value = districtID;
                    document.getElementById('txtProvince3').value = provinceName;
                   document.getElementById('txtDistrict3').value = districtName;
                   
                }";

            this.ClientScript.RegisterStartupScript(Page.GetType(),
            "UpdateValues2", updateValuesScript2.ToString(), true);

            btnFindProvince.Attributes.Add("onclick", "openPopUp('FindProvince.aspx','open')");


        }
        protected string GetUserLoginEmpNo()
        {
            string t = "";
            try
            {
                if (Session["UserLoginInfo"] != null)
                {
                    Entities db = new Entities();
                    var u = (TB_USER[])Session["UserLoginInfo"];
                    int _UID = Convert.ToInt32(u.Single().ID);
                    var au = from ft in db.TB_USER_LEVEL
                             where ft.USER_ID == _UID
                             select ft;
                    int _le = Convert.ToInt32(au.Single().LEVEL_ID);
                    var le = from xx in db.TB_LEVEL
                             where xx.ID == _le
                             select xx;
                    _currentUserAuthority = le.Single().REMARK;
                    return u.Single().EMPNO;
                }
            }
            catch (Exception)
            {
                t = "";
            }
            return t;
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string m = "0";
            string s = "0";
            try
            {
                m = Request.QueryString["m"].ToString();
            }
            catch (Exception)
            {
            }
            try
            {
                s = Request.QueryString["s"].ToString();
            }
            catch (Exception)
            {
            }
            if (m == "1" && !string.IsNullOrEmpty(s))
            {
                doSave(lblShopCode.Text);
            }
            else
                doAdd();

        }
        protected void LoadDataInModifyMode(string _shopcode)
        {
            Entities db = new Entities();
            var sh = from t in db.TB_CM_SHOP_INF
                     where t.SHOP_CODE == _shopcode
                     select t;
            if (sh.Count() == 1)
            {
                txtBillTo2.Text = loadBillTo(_shopcode);
                txtBillCodeHidden.Text = txtBillTo2.Text;
                if (sh.Single().REG_ID != null)
                    DBAction.SetSelected(dropArea, sh.Single().REG_ID.ToString());
                //txtBillToName2.Text = DBAction.GetBillToName(sh.Single().BILLTO_CODE);
                //txtCusCode2.Text = sh.Single().CUSTOMER_CODE;
                //txtCusAddress2.Text = DBAction.GetCusCodeAddress(sh.Single().CUSTOMER_CODE);
                if (!string.IsNullOrEmpty(sh.Single().PROVINCE_CODE))
                    txtProvince2.Text = sh.Single().PROVINCE_CODE;
                if (!string.IsNullOrEmpty(sh.Single().DIST_CODE))
                    txtDistrict2.Text = sh.Single().DIST_CODE;
                txtProvince3.Text = DBAction.GetProvinceName(Convert.ToInt32(sh.Single().PROVINCE_CODE));
                txtDistrict3.Text = DBAction.GetDistricName(Convert.ToInt32(sh.Single().DIST_CODE));

                lblShopCode.Text = sh.Single().SHOP_CODE;
                txtBillCode.Text = txtBillTo2.Text;
                //txtBillName.Text = DBAction.GetBillToName(sh.Single().BILLTO_CODE);
                if (!string.IsNullOrEmpty(sh.Single().REG_ID))
                    DBAction.SetSelected(dropArea, sh.Single().REG_ID);
                if (!string.IsNullOrEmpty(sh.Single().SHOP_TYPE))
                    DBAction.SetSelected(dropShopType, sh.Single().SHOP_TYPE);
                //txtCusCode.Text = sh.Single().CUSTOMER_CODE;
                //txtCusAddress.Text = DBAction.GetCusCodeAddress(sh.Single().CUSTOMER_CODE);
                if (!string.IsNullOrEmpty(sh.Single().OWNER_NAME))
                    txtOwnerName.Text = sh.Single().OWNER_NAME;
                if (!string.IsNullOrEmpty(sh.Single().SHOP_NAME))
                    txtName.Text = sh.Single().SHOP_NAME;
                if (!string.IsNullOrEmpty(sh.Single().OWNER_EMAIL))
                    txtOwnerEmail.Text = sh.Single().OWNER_EMAIL;
                if (!string.IsNullOrEmpty(sh.Single().ADDRESS))
                    txtAddress.Text = sh.Single().ADDRESS;
                if (!string.IsNullOrEmpty(sh.Single().CELL_NO_2))
                    txtCell2.Text = sh.Single().CELL_NO_2;
                txtCell1.Text = sh.Single().CELL_NO_1;
                txtCell1Hidden.Text = sh.Single().CELL_NO_1;
                if (!string.IsNullOrEmpty(sh.Single().CELL_NO_2))
                    txtCell2Hidden.Text = sh.Single().CELL_NO_2;
                if (!string.IsNullOrEmpty(sh.Single().ISDN_NO))
                    txtISDN.Text = sh.Single().ISDN_NO;
                txtProvince.Text = DBAction.GetProvinceName(Convert.ToInt32(sh.Single().PROVINCE_CODE));
                txtDistrict.Text = DBAction.GetDistricName(Convert.ToInt32(sh.Single().DIST_CODE));
                if (sh.Single().CHANNEL.ToUpper() == "Y")
                    DBAction.SetSelected(dropChannel, "Y");
                else
                    DBAction.SetSelected(dropChannel, "N");
                if (sh.Single().USE_FLAG.ToLower() == "y")
                    chkEnable.Checked = true;
                else
                    chkEnable.Checked = false;
            }
            else
            {
                ShowError("Error while get shop information.");
            }
        }

        private void LoadArea()
        {
            Entities db = new Entities();
            try
            {
                var b = from t in db.TB_CM_REGION
                        where t.ID != "00"
                        select t;

                dropArea.DataSource = b;
                dropArea.DataTextField = "NAME";
                dropArea.DataValueField = "ID";
                dropArea.DataBind();
            }
            catch (Exception)
            {
            }
        }
        private string loadBillTo(string shcode)
        {
            Entities db = new Entities();
            string st = "";
            try
            {
                var b = from t in db.TB_CM_SHOP_BILLTO
                        where t.SHOP_CODE == shcode && t.USE_FLAG.ToLower() == "y"
                        select t;
                foreach (var item in b)
                {
                    st += item.BILLTO_CODE + ",";
                }
                return st;
            }
            catch (Exception ee)
            {
                return "Error while get Bill Code";
            }
        }
        protected void doAdd()
        {
            Entities db = new Entities();
            TB_CM_SYS_LOG lg = new TB_CM_SYS_LOG();
            if (DBAction.LogUser == true)
            {
                lg.ID = String.Format("{0:u}", DateTime.Now);
                lg.SEQ_KEY = Guid.NewGuid().ToString();
                lg.ENTRY_USER_ID = _currentUserEmpNo;
                lg.ENTRY_DATE_TIME = DateTime.Now;
                lg.TITLE = _currentUserEmpNo + " add new shop";
            }
            try
            {
                if (string.IsNullOrEmpty(txtBillTo2.Text)) //|| string.IsNullOrEmpty(txtCusCode2.Text) 
                {
                    ShowWarning("User must select Bill To fisrt");
                    return;
                }
                if (string.IsNullOrEmpty(txtName.Text))
                {
                    ShowWarning("User must input ShopName");
                    txtName.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtAddress.Text))
                {
                    ShowWarning("User must input Address");
                    txtAddress.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtCell1.Text))
                {
                    ShowWarning("User must input Cell#1");
                    txtCell1.Focus();
                    return;
                }
                else
                {
                    if (txtCell1.Text.Length < 9 || txtCell1.Text.Length > 12)
                    {
                        ShowWarning("Cell#1 must greater than 9 and lower than 12");
                        txtCell1.Focus();
                        return;
                    }
                    else
                    {
                        if (txtCell1.Text.StartsWith("09") == true || txtCell1.Text.StartsWith("01") == true || txtCell1.Text.StartsWith("06") == true)
                        {
                        }
                        else
                        {
                            ShowWarning("Cell#1 must start with '09' or '01' or '06'");
                            txtCell1.Focus();
                            return;
                        }
                    }

                }
                if (string.IsNullOrEmpty(txtProvince2.Text))
                {
                    ShowWarning("Please select Province and District");
                    btnFindProvince.Focus();
                    return;
                }
                string query = "";
                string err = "";
                TB_CM_SHOP_INF sh = new TB_CM_SHOP_INF();
                var _max = (from t in db.TB_CM_SHOP_INF select t.SHOP_CODE.Replace("EASV", "")).Max();
                int _ID = Convert.ToInt32(_max) + 1;
                string st = _ID.ToString();
                while (st.Length < 4)
                {
                    st = "0" + st;
                }
                sh.SHOP_CODE = "EASV" + st;
                if (!DBAction.ShopNameExistOrNot(txtName.Text.Trim().ToLower()) == true)
                    sh.SHOP_NAME = (txtName.Text);
                else
                {
                    ShowWarning("Shop Name exists");
                    txtName.Focus();
                    return;
                }
                sh.ADDRESS = txtAddress.Text;
                sh.CELL_NO_1 = "84" + txtCell1.Text.Trim().Remove(0, 1);
                if (DBAction.ShopCellExistOrNot(sh.CELL_NO_1) == true)
                {
                    ShowWarning("Shop Cell exists");
                    txtCell1.Focus();
                    return;
                }
                sh.DIST_CODE = txtDistrict2.Text;
                sh.PROVINCE_CODE = txtProvince2.Text;
                sh.BILLTO_CODE = GetdefaultBillto(txtBillTo2.Text);
                sh.CUSTOMER_CODE = DBAction.GetCustomerCodeByBillTo(sh.BILLTO_CODE);
                sh.SHOP_TYPE = dropShopType.SelectedValue;
                sh.USE_FLAG = "Y";
                if (!string.IsNullOrEmpty(txtISDN.Text))
                    sh.ISDN_NO = txtISDN.Text;
                //sh.AREA_CODE = dropArea.SelectedValue;
                sh.REG_ID = dropArea.SelectedValue;
                if (!string.IsNullOrEmpty(txtCell2.Text))
                {
                    if (txtCell2.Text.Length < 9 || txtCell2.Text.Length > 12)
                    {
                        ShowWarning("Cell#2 must greater than 9 and lower than 12");
                        txtCell2.Focus();
                        return;
                    }
                    else
                    {
                        if (txtCell2.Text.StartsWith("09") == true || txtCell2.Text.StartsWith("01") == true || txtCell2.Text.StartsWith("06") == true)
                        {
                            sh.CELL_NO_2 = "84" + txtCell2.Text.Trim().Remove(0, 1);
                            if (DBAction.ShopCellExistOrNot(sh.CELL_NO_2) == true)
                            {
                                ShowWarning("Shop Cell exists");
                                txtCell2.Focus();
                                return;
                            }
                        }
                        else
                        {
                            ShowWarning("Cell#2 must start with '09' or '01' or '06'");
                            txtCell2.Focus();
                            return;
                        }
                    }
                }
                if (!string.IsNullOrEmpty(txtOwnerName.Text))
                    sh.OWNER_NAME = txtOwnerName.Text;
                if (!string.IsNullOrEmpty(txtOwnerEmail.Text))
                    sh.OWNER_EMAIL = txtOwnerEmail.Text;
                sh.CHANNEL = dropChannel.SelectedValue;
                sh.CREATE_DATE = DateTime.Now;
                sh.CREATE_USER = _currentUserEmpNo;
                //===========================================
                query = "Insert into TB_CM_SHOP_INF (SHOP_CODE,SHOP_NAME,ADDRESS,REG_ID,BILLTO_CODE,CELL_NO#1,CELL_NO#2,CUSTOMER_CODE,DIST_CODE,PROVINCE_CODE,ISDN_NO,OWNER_EMAIL,OWNER_NAME,USE_FLAG,CHANNEL,SHOP_TYPE,CREATE_DATE) values (";
                query += "'" + sh.SHOP_CODE + "',";
                query += "'" + sh.SHOP_NAME + "',";
                query += "'" + sh.ADDRESS + "',";
                query += "'" + sh.REG_ID + "',";
                query += "'" + sh.BILLTO_CODE + "',";
                query += "'" + sh.CELL_NO_1 + "',";
                query += "'" + sh.CELL_NO_2 + "',";
                query += "'" + sh.CUSTOMER_CODE + "',";
                query += "'" + sh.DIST_CODE + "',";
                query += "'" + DBAction.GetProvinceID(Convert.ToInt32(sh.DIST_CODE)).ToString() + "',";
                query += "'" + sh.ISDN_NO + "',";
                query += "'" + sh.OWNER_EMAIL + "',";
                query += "'" + sh.OWNER_NAME + "',";
                query += "'" + "Y" + "',";
                query += "'" + sh.CHANNEL + "',";
                query += "'" + sh.SHOP_TYPE + "',";
                query += "SYSDATE";
                query += ")";

                OracleCommand cmd = DBAction.con.CreateCommand();
                OracleParameter param = new OracleParameter();
                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;
                var x = cmd.ExecuteScalar();
                if (DBAction.LogUser == true)
                {
                    lg.ACTION1 = query + " - ";
                }

                if (x != null)
                    err += x.ToString() + "\n";
                else
                {
                    if (!string.IsNullOrEmpty(err.Replace("\n", "")))
                    {
                        ShowError("Error of: " + query + ":" + err);
                        return;
                    }
                    //db.TB_CM_SHOP_INF.AddObject(sh);

                    //if insert Shop ok, insert Cell #1, #2, if error, ko insert
                    //sh.CELL_NO_1 = txtCell1.Text.Replace("+", "");
                    TB_CM_SHOP_CELL c;
                    {
                        c = new TB_CM_SHOP_CELL();
                        c.SHOP_ID = "EASV" + st;
                        c.SHOP_CELL = txtCell1.Text.Replace("+", "");
                        c.CREATE_DATE = DateTime.Now;
                        c.CREATE_USER = _currentUserEmpNo;
                        c.USE_FLAG = "Y";
                        db.TB_CM_SHOP_CELL.AddObject(c);
                        if (DBAction.LogUser == true)
                        {
                            lg.ACTION2 = "Add new shop cell " + c.SHOP_ID + "|" + c.SHOP_CELL;
                        }
                        if (!string.IsNullOrEmpty(txtCell2.Text))
                        {
                            c = new TB_CM_SHOP_CELL();
                            c.SHOP_ID = "EASV" + st;
                            c.SHOP_CELL = txtCell2.Text;
                            c.CREATE_DATE = DateTime.Now;
                            c.CREATE_USER = _currentUserEmpNo;
                            c.USE_FLAG = "Y";
                            db.TB_CM_SHOP_CELL.AddObject(c);
                            if (DBAction.LogUser == true)
                            {
                                lg.ACTION3 = "Add new shop cell " + c.SHOP_ID + "|" + c.SHOP_CELL;
                            }
                        }
                    }

                    //if insert Shop ok, insert BL, if error, ko insert
                    string[] mangBillto = txtBillTo2.Text.Split(',');
                    foreach (string item in mangBillto)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            TB_CM_SHOP_BILLTO s = new TB_CM_SHOP_BILLTO();
                            s.BILLTO_CODE = item;
                            s.SHOP_CODE = "EASV" + st;
                            s.CREATE_DATE = DateTime.Now;
                            s.CREATE_USER = _currentUserEmpNo;
                            s.USE_FLAG = "Y";

                            db.TB_CM_SHOP_BILLTO.AddObject(s);
                            if (DBAction.LogUser == true)
                            {
                                lg.ACTION4 = "Add new Bill " + s.BILLTO_CODE + "|" + s.SHOP_CODE;
                            }
                        }
                    }
                    if (DBAction.LogUser == true)
                        db.TB_CM_SYS_LOG.AddObject(lg);
                    db.SaveChanges();
                    MessageBox.Show("Add new shop code: " + "EASV" + st);
                }
            }
            catch (Exception ee)
            {
                if (ee.InnerException != null)
                    MessageBox.Show(ee.InnerException.Message);
                else
                    MessageBox.Show(ee.Message);
            }
        }

        private string GetdefaultBillto(string p)
        {
            string[] mang = p.Split(',');
            foreach (string item in mang)
            {
                if (!string.IsNullOrEmpty(item))
                    return item;
            }
            return "Error While get Default Bill to";
        }
        protected void doSave(string shCode)
        {
            string debug = "";
            Entities db = new Entities();
            //for log
            TB_CM_SYS_LOG lg = new TB_CM_SYS_LOG();
            if (DBAction.LogUser == true)
            {
                lg.ID = String.Format("{0:u}", DateTime.Now);
                lg.SEQ_KEY = Guid.NewGuid().ToString();
                lg.ENTRY_USER_ID = _currentUserEmpNo;
                lg.ENTRY_DATE_TIME = DateTime.Now;
                lg.TITLE = _currentUserEmpNo + " modify shop information";
            }
            try
            {
                //if (string.IsNullOrEmpty(txtCusCode2.Text) || string.IsNullOrEmpty(txtBillTo2.Text))
                //{
                //    ShowWarning("User must select Bill To fisrt");
                //    return;
                //}
                if (string.IsNullOrEmpty(txtName.Text))
                {
                    ShowWarning("User must input ShopName");
                    txtName.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtAddress.Text))
                {
                    ShowWarning("User must input Address");
                    txtAddress.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtCell1.Text))
                {
                    ShowWarning("User must input Cell #1");
                    txtCell1.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtProvince2.Text))
                {
                    ShowWarning("Please select Province and District");
                    btnFindProvince.Focus();
                    return;
                }
                //cap nhat shop_INF
                TB_CM_SHOP_INF sh = new TB_CM_SHOP_INF();
                TB_CM_SHOP_INF shopToRollBack = db.TB_CM_SHOP_INF.Single(t => t.SHOP_CODE == lblShopCode.Text);

                sh.SHOP_NAME = txtName.Text;
                sh.ADDRESS = txtAddress.Text;
                sh.BILLTO_CODE = GetdefaultBillto(txtBillTo2.Text);
                if (txtCell1.Text.IndexOf("+") != -1)
                    sh.CELL_NO_1 = CheckPhoneNo(txtCell1.Text.Replace("+", ""));
                else
                    sh.CELL_NO_1 = CheckPhoneNo(txtCell1.Text);
                //sh.CUSTOMER_CODE = txtCusCode2.Text;  // txtlblCusCode.Text.Substring(0, txtlblCusCode.Text.IndexOf(" - "));
                if (!string.IsNullOrEmpty(txtCell2.Text))
                    sh.CELL_NO_2 = CheckPhoneNo(txtCell2.Text);
                sh.DIST_CODE = txtDistrict2.Text;
                sh.PROVINCE_CODE = txtProvince2.Text;
                if (chkEnable.Checked)
                    sh.USE_FLAG = "Y";
                else
                    sh.USE_FLAG = "N";
                if (!string.IsNullOrEmpty(txtISDN.Text))
                    sh.ISDN_NO = txtISDN.Text;
                //sh.AREA_CODE = dropArea.SelectedValue;
                sh.REG_ID = dropArea.SelectedValue;

                if (!string.IsNullOrEmpty(txtOwnerName.Text))
                    sh.OWNER_NAME = txtOwnerName.Text;
                if (!string.IsNullOrEmpty(txtOwnerEmail.Text))
                    sh.OWNER_EMAIL = txtOwnerEmail.Text;
                sh.CHANNEL= dropChannel.SelectedValue;
                sh.SHOP_TYPE = dropShopType.SelectedValue;
                sh.UPDATE_DATE = DateTime.Now;

                //EF save error, nen fai save = tay 
                string query = "";
                query += "UPDATE TB_CM_SHOP_INF SET ";
                query += "BILLTO_CODE = '" + sh.BILLTO_CODE + "' , ";
                query += "SHOP_NAME = '" + sh.SHOP_NAME + "', ";
                query += "ADDRESS = '" + sh.ADDRESS + "', ";
                query += "CELL_NO#1 = '" + sh.CELL_NO_1 + "', ";
                query += "CELL_NO#2 = '" + sh.CELL_NO_2 + "', ";
                query += "DIST_CODE = '" + sh.DIST_CODE + "', ";
                query += "PROVINCE_CODE = '" + sh.PROVINCE_CODE + "', ";
                query += "UPDATE_DATE = SYSDATE, ";
                query += "UPDATE_USER = '" + _currentUserEmpNo + "', ";
                query += "CHANNEL = '" + sh.CHANNEL + "', ";
                query += "ISDN_NO = '" + sh.ISDN_NO + "', ";
                query += "USE_FLAG = '" + sh.USE_FLAG + "', ";
                query += "OWNER_NAME = '" + sh.OWNER_EMAIL + "', ";
                query += "OWNER_EMAIL = '" + sh.OWNER_NAME + "', ";
                query += "REG_ID = '" + sh.REG_ID + "', ";
                query += "SHOP_TYPE = '" + sh.SHOP_TYPE + "' ";
                query += " WHERE SHOP_CODE = '" + lblShopCode.Text + "' ";

                OracleCommand cmd = new OracleCommand();
                cmd = DBAction.con.CreateCommand();
                OracleParameter param = new OracleParameter();
                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;
                var x = cmd.ExecuteScalar();
                if (DBAction.LogUser == true)
                {
                    lg.ACTION1 = query + " - ";
                }
                if (x != null)
                    debug += x.ToString() + "\n";
                else
                    debug += "\n";

                if (!string.IsNullOrEmpty(debug.Replace("\n", "")))
                {
                    string lskdfjlskfj = DoRollBackShopINF(sh, shopToRollBack);
                    if (string.IsNullOrEmpty(lskdfjlskfj))
                        MessageBox.Show(debug);
                    else
                        MessageBox.Show(debug + "\n" + lskdfjlskfj);
                    if (DBAction.LogUser == true)
                    {
                        lg.ACTION2 = "Rollback shop information: " + shopToRollBack.ToString() + " - " + lskdfjlskfj;
                    }
                    return;
                }
                else
                    debug += "1. Update basic shop info done \n";

                //////////////////////////////////////////Update CELL
                if (txtCell1.Text.Trim() != txtCell1Hidden.Text.Trim())
                {
                    //cap nhat so dien thoai cu la ko su dung
                    try
                    {
                        var cel1 = db.TB_CM_SHOP_CELL.Single(t => t.SHOP_CELL == txtCell1Hidden.Text && t.USE_FLAG.ToLower() == "y");
                        cel1.USE_FLAG = "N";
                        cel1.MODIFY_DATE = DateTime.Now;
                        cel1.MODIFY_USER = _currentUserEmpNo;
                        debug += "2. Deactive Cell No: " + txtCell1Hidden.Text + " done \n";
                        if (DBAction.LogUser == true)
                        {
                            lg.ACTION3 = "Deactive Cell No: " + txtCell1Hidden.Text + " - Done";
                        }
                    }
                    catch (Exception ee)
                    {
                        //no result,or add new or admin check
                        if (!ee.Message.ToLower().Contains("sequence contains no elements"))
                        {
                            debug += ("2.[Error] Cannot Deactive Cell No : " + txtCell1Hidden.Text + " to 'N'. Detail: " + ee.Message + "\n");
                            if (DBAction.LogUser == true)
                            {
                                lg.ACTION3 = "[Error] Cannot Deactive Cell No : " + txtCell1Hidden.Text + " to 'N'. Detail: " + ee.Message;
                            }
                        }
                    }


                    //add new fone va set la su dung(fai add de luu history)
                    TB_CM_SHOP_CELL c = new TB_CM_SHOP_CELL();
                    c.SHOP_ID = shCode;
                    c.SHOP_CELL = CheckPhoneNo(txtCell1.Text);
                    c.CREATE_DATE = DateTime.Now;
                    c.CREATE_USER = _currentUserEmpNo;
                    c.USE_FLAG = "Y";
                    db.TB_CM_SHOP_CELL.AddObject(c);
                    debug += "3. Add new Cell No: " + txtCell1.Text + " done \n";
                    if (DBAction.LogUser == true)
                    {
                        lg.ACTION4 = "Add new Cell No: " + txtCell1.Text + " - done";
                    }
                }
                if (!string.IsNullOrEmpty(txtCell2.Text.Trim()))
                {
                    if (txtCell2.Text.Trim() != txtCell2Hidden.Text.Trim())
                    {
                        //cap nhat so dien thoai cu la ko su dung
                        try
                        {
                            var cel2 = db.TB_CM_SHOP_CELL.Single(t => t.SHOP_CELL == txtCell2Hidden.Text && t.SHOP_ID == shCode && t.USE_FLAG.ToLower() == "y");
                            cel2.USE_FLAG = "N";
                            cel2.MODIFY_DATE = DateTime.Now;
                            cel2.MODIFY_USER = _currentUserEmpNo;
                            debug += "4. Deactive Cell No: " + txtCell2Hidden.Text + " done \n";
                            if (DBAction.LogUser == true)
                            {
                                lg.ACTION5 = "Deactive Cell No: " + txtCell2Hidden.Text + " - done";
                            }
                        }
                        catch (Exception ee)
                        {
                            //ko co' cel nao, hoac la add new hoac la unknown Error.
                            if (!ee.Message.ToLower().Contains("sequence contains no elements"))
                            {
                                debug += ("4.[Error] Cannot Deactive Cell No : " + txtCell2Hidden.Text + " to 'N'. Detail: " + ee.Message + "\n");
                                if (DBAction.LogUser == true)
                                {
                                    lg.ACTION5 = "[Error] Cannot Deactive Cell No : " + txtCell2Hidden.Text + " to 'N'. Detail: " + ee.Message;
                                }
                            }
                        }

                        //add new fone va set la su dung(fai add de luu history)
                        TB_CM_SHOP_CELL c = new TB_CM_SHOP_CELL();
                        c.SHOP_ID = shCode;
                        c.SHOP_CELL = CheckPhoneNo(txtCell2.Text);
                        c.CREATE_DATE = DateTime.Now;
                        c.CREATE_USER = _currentUserEmpNo;
                        c.USE_FLAG = "Y";
                        db.TB_CM_SHOP_CELL.AddObject(c);
                        debug += "5. Add new Cell No: " + txtCell2.Text + " done \n";
                        if (DBAction.LogUser == true)
                        {
                            lg.ACTION6 = "Add new Cell No: " + txtCell2.Text + " - done";
                        }
                    }
                }

                //////////////////////////////////////////Update BIll TO
                if (txtBillTo2.Text != txtBillCodeHidden.Text)
                {
                    //check xem co' remove di ko(1 thang cu ko co mat trong chuoi moi)
                    string[] BillToASIF = txtBillCodeHidden.Text.Split(',');
                    string[] BillToTOBE = txtBillTo2.Text.Split(',');
                    int dem = 0;
                    int job = 6;
                    int totalJob = 0;
                    foreach (string old in BillToASIF)
                    {
                        if (!string.IsNullOrEmpty(old))
                        {
                            var i = txtBillTo2.Text.IndexOf(old);
                            if (i == -1) //1 thang cu ko co mat trong chuoi moi
                            {
                                //update thagn nay use_flag = N
                                var s = db.TB_CM_SHOP_BILLTO.Single(t => t.SHOP_CODE == shCode && t.BILLTO_CODE == old);
                                try
                                {
                                    s.USE_FLAG = "N";
                                    s.MODIFY_DATE = DateTime.Now;
                                    s.MODIFY_USER = _currentUserEmpNo;
                                    debug += (job + dem) + ". Deactive BILLTO: " + old + " done \n";
                                    if (DBAction.LogUser == true)
                                    {
                                        lg.ACTION7 = (job + dem) + ". Deactive BILLTO: " + old + " - done";
                                    }
                                }
                                catch (Exception ee)
                                {
                                    debug += (job + dem) + (".[Error] Cannot Deactive BILLTO : " + old + " to 'N'. Detail: " + ee.Message + "\n");
                                    if (DBAction.LogUser == true)
                                    {
                                        lg.ACTION7 = "[Error] Cannot Deactive BILLTO : " + old + " to 'N'. Detail: " + ee.Message;
                                    }
                                }
                            }
                        }
                        dem++;
                    }
                    totalJob = dem + job;
                    dem = 0;
                    //check xem co' add them vao ko(1 thang moi ko co mat trong chuoi cu)
                    TB_CM_SHOP_BILLTO _s;
                    foreach (string _new in BillToTOBE)
                    {
                        if (!string.IsNullOrEmpty(_new))
                        {
                            var i = txtBillCodeHidden.Text.IndexOf(_new);
                            if (i == -1) //1 thang moi ko co mat trong chuoi cu
                            {
                                //add them vao 
                                try
                                {
                                    _s = new TB_CM_SHOP_BILLTO();
                                    _s.SHOP_CODE = shCode;
                                    _s.BILLTO_CODE = _new;
                                    _s.CREATE_DATE = DateTime.Now;
                                    _s.CREATE_USER = _currentUserEmpNo;
                                    _s.USE_FLAG = "Y";
                                    db.TB_CM_SHOP_BILLTO.AddObject(_s);
                                    debug += (totalJob + dem) + ". Add BILLTO: " + _new + " done \n";
                                    if (DBAction.LogUser == true)
                                    {
                                        lg.ACTION8 = (totalJob + dem) + ". Add BILLTO: " + _new + " - Done";
                                    }
                                }
                                catch (Exception ee)
                                {
                                    debug += (totalJob + dem) + (". Cannot Add BILLTO : " + _new + ". Detail: " + ee.Message + "\n");
                                    if (DBAction.LogUser == true)
                                    {
                                        lg.ACTION8 = (totalJob + dem) + ". Cannot Add BILLTO : " + _new + ". Detail: " + ee.Message;
                                    }
                                }
                            }
                        }
                        dem++;
                    }
                }
                if (DBAction.LogUser == true)
                    db.TB_CM_SYS_LOG.AddObject(lg);

                db.SaveChanges();
                MessageBox.Show(debug);
            }
            catch (Exception ee)
            {
                if (ee.InnerException != null)
                    MessageBox.Show(ee.InnerException.Message);
                else
                    MessageBox.Show(ee.Message);
            }

        }

        //===================//===================//===================//===================//===================//==================
        public string CheckPhoneNo(string fone)
        {
            if (!fone.Trim().StartsWith("84"))
            {
                if (fone.Trim().StartsWith("0"))
                    return "84" + fone.Trim().Substring(1);
                else
                    return "84" + fone.Trim();
            }
            else
                return fone.Trim();
        }
        public string DoRollBackShopINF(TB_CM_SHOP_INF sNew, TB_CM_SHOP_INF sOld)
        {
            try
            {
                string query = "";
                string debug = "";
                query += "UPDATE TB_CM_SHOP_INF SET ";
                query += "BILLTO_CODE = '" + sOld.BILLTO_CODE + "' , ";
                query += "SHOP_NAME = '" + sOld.SHOP_NAME + "', ";
                query += "ADDRESS = '" + sOld.ADDRESS + "', ";
                query += "CELL_NO#1 = '" + sOld.CELL_NO_1 + "', ";
                query += "CELL_NO#2 = '" + sOld.CELL_NO_2 + "', ";
                query += "DIST_CODE = '" + sOld.DIST_CODE + "', ";
                query += "PROVINCE_CODE = '" + sOld.PROVINCE_CODE + "', ";
                //query += "UPDATE_DATE = ";
                query += "UPDATE_USER = '" + _currentUserEmpNo + "', ";
                query += "DEALER_YN = '" + sOld.CHANNEL + "', ";
                query += "ISDN_NO = '" + sOld.ISDN_NO + "', ";
                query += "USE_FLAG = '" + sOld.USE_FLAG + "', ";
                query += "OWNER_NAME = '" + sOld.OWNER_NAME + "', ";
                query += "OWNER_EMAIL = '" + sOld.OWNER_EMAIL + "', ";
                query += "AREA_CODE = '" + sOld.AREA_CODE + "' ";
                query += " WHERE SHOP_CODE = '" + sOld.SHOP_CODE + "' ";
                debug += DBAction.RunStore(query);
                return debug; //neu ko loi, debug = "";
            }
            catch (Exception ee)
            {
                return ee.Message;
            }

        }
        public void ShowError(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification error\"><div class=\"text\"><p><strong>" + er + " </strong> </p></div></div>", false);
        }
        public void ShowError(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification error\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }
        public void ShowInfo(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification info\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
        }
        public void ShowInfo(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification info\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }
        public void ShowWarning(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification warning\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
        }
        public void ShowWarning(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification warning\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }
        public void ShowSuccess(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification success\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
        }
        public void ShowSuccess(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification success\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }
        public void ShowTip(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification tip\"><div class=\"text\"><p><strong> " + er + "</strong> </p></div></div>", false);
        }
        public void ShowTip(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification tip\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }

    }
}